package cn.conac.rc.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.conac.rc.entity.AreaEntity;
import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.repository.AreaRepository;
import cn.conac.rc.vo.AreaVo;

@Service
@Transactional
public class AreaService extends GenericService<AreaEntity, String> {

    @Autowired
    private AreaRepository repository;

    /**
     * 计数查询
     * @param vo
     * @return 计数结果
     */
    public long count(AreaVo vo) {
        return super.count(this.createCriteria(vo));
    }

    /**
     * 动态查询，分页，排序查询
     * @param vo
     * @return Page
     * @throws Exception
     */
    public Page<AreaEntity> list(AreaVo vo) throws Exception {
        try {
            Sort sort = new Sort(Direction.ASC, "id");// TODO 可选的排序
            Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
            Criteria<AreaEntity> dc = this.createCriteria(vo);
            return repository.findAll(dc, pageable);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public List<AreaEntity> getListByCriteria(AreaEntity areaParam) {
        Criteria<AreaEntity> criteria = this.createCriteria(areaParam);
        // 创建排序（权重）
        Sort sort = new Sort(Direction.ASC, "weight");
        // 根据动态查询条件及排序依据查询集合
        return this.findAll(criteria, sort);
    }

    public List<AreaEntity> getAreaListByPid(String pid) {
        return repository.findByPid(pid);
    }

    /**
     * 拼接查询条件
     * @param areaParem 地区信息
     * @return Criteria<AreaEntity> 地区JPA封装类
     * @author haocm
     */
    private Criteria<AreaEntity> createCriteria(AreaEntity areaParam) {
        Criteria<AreaEntity> dc = new Criteria<AreaEntity>();
        if (StringUtils.isNotBlank(areaParam.getCode())) {
            dc.add(Restrictions.eq("code", areaParam.getCode(), true));
        }
        if (StringUtils.isNotBlank(areaParam.getPid())) {
            dc.add(Restrictions.eq("pid", areaParam.getPid(), true));
        }
        if (areaParam.getLvl() != null && areaParam.getLvl() != 0) {
            dc.add(Restrictions.eq("lvl", areaParam.getLvl(), true));
        }
        return dc;
    }
    
    /**
	 * 保存当前部门同时更新父部门的hasChild字段
	 * 
	 * @param areaCode  地区编码
	 * @param openPilotType 是否同时开通下级地区（“1”：是 ,“0”只开通自己）
	 * @return void
	 */
	public int  updateTypeByCond(String areaCode, String openPilotType) {
		int cnt = 0;
		if(StringUtils.isNotBlank(areaCode) 
				&& !"000000000".equals(areaCode)) {
			if("1".equals(openPilotType)) {
				String areaCodeLike =areaCode;
				if(areaCode.endsWith("0000000")) {
					areaCodeLike = areaCode.substring(0, 2);
				} else if(areaCode.endsWith("0000")) {
					areaCodeLike = areaCode.substring(0, 5);
				}
				if(areaCodeLike.length() != 9) {
					areaCodeLike +=  "%";
				}
				cnt = repository.updateTypeByAreaCodeLike(areaCodeLike);
			} else {
				cnt= repository.updateTypeByAreaCode(areaCode);
			}
		}
		return cnt;
	}

	/**
	 * 动态查询，排序查询
	 * @param vo
	 * @return List<AreaEntity>
	 * @throws Exception
	 */
	public List<AreaEntity> findListByPara(AreaVo vo) throws Exception {
		try {
			Sort sort = new Sort(Direction.ASC, "code", "weight");
			Criteria<AreaEntity> dc = this.createCriteria(vo);
			return repository.findAll(dc, sort);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * @param param
	 * @return Criteria
	 */
	private Criteria<AreaEntity> createCriteria(AreaVo param) {
		Criteria<AreaEntity> dc = new Criteria<AreaEntity>();
		
		if(param.getNoSelfFlag()!= null && param.getNoSelfFlag().intValue() == 1) {
			if(StringUtils.isNotBlank(param.getCode())) {
				dc.add(Restrictions.ne("code", param.getCode(), true));
			}
		} 
		
		if(StringUtils.isNotBlank(param.getName())) {
			dc.add(Restrictions.like("name", param.getName(), true));
		}
		
		if(param.getLvl() != null) {
			dc.add(Restrictions.eq("lvl", param.getLvl(), true));
		}
	
		if(param.getIsPublic() != null) {
			dc.add(Restrictions.eq("isPublic", param.getIsPublic(), true));
		}
		return dc;
	}
}
